package com.hyjx.framework.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyjx.framework.orm.dao.Pager;
import oracle.sql.CLOB;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;

/**
 * 系统工具类
 *
 * @author Administrator
 */
public class CommonUtil {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 获取32位uuid
     *
     * @return
     */
    public static String getUUID32() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "");
    }
    
    /**
     * 获取当前日志的字符串 yyyy-mm-dd
     *
     * @return
     */
    public static String getCurrentDateStr() {
        Date date = new Date();
        return sdf.format(date);
    }
    
    /**
     * 获取自定义格式的当前日志字符串
     *
     * @param date
     * @return
     */
    public static Date formatDate(String date) {
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 根据对象得到不同类型数据库连接
     *
     * @param obj
     * @return
     */
    public static Connection getConnection(Object obj) {
        Connection connection = null;
        try {
            String db_type = (String) BeanUtils.getProperty(obj, "db_type");
            String db_ip = (String) BeanUtils.getProperty(obj, "db_ip");
            String db_username = (String) BeanUtils.getProperty(obj, "db_username");
            String db_password = (String) BeanUtils.getProperty(obj, "db_password");
            String db_port = (String) BeanUtils.getProperty(obj, "db_port");
            String db_name = (String) BeanUtils.getProperty(obj, "db_name");
            Properties props = new Properties();
            props.put("user", db_username);
            props.put("password", db_password);
            String url = "";
            // 数据库类型
            if ("1".equals(db_type)) {
                Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
                url = "jdbc:oracle:thin:@" + db_ip + ":" + db_port + ":" + db_name;
            } else if ("2".equals(db_type)) {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
                url = "jdbc:sqlserver://" + db_ip + ":" + db_port + ";DatabaseName=" + db_name;
            } else if ("3".equals(db_type)) {
                Class.forName("org.gjt.mm.mysql.Driver").newInstance();
                url = "jdbc:mysql://" + db_ip + ":" + db_port + "/" + db_name;
            } else if ("4".equals(db_type)) {
                Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
                url = "jdbc:sybase:Tds:" + db_ip + ":" + db_port + "/" + db_name;
            }
            connection = DriverManager.getConnection(url, props);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    /**
     * 将对象转化成json字符串
     *
     * @param obj
     * @throws Exception
     */
    public static String getJsonString(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        String resultStr = "{}";
        try {
            resultStr = mapper.writeValueAsString(obj);
            if (resultStr.contains("\":null,\""))
                resultStr = resultStr.replaceAll("\":null,\"", "\":\"\",\"");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultStr;
    }
    
    /**
     * 将page对象转换成json对象
     *
     * @param pager pager分页结果对象
     * @return json
     */
    public static String getPageJsonStr(Pager pager) {
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        sb.append("\"total\": " + pager.getRowCount() + ",");
        sb.append("\"rows\": ");
        sb.append(CommonUtil.getJsonString(pager.getResultList()).toString());
        sb.append("}");
        return sb.toString();
    }
    
    /**
     * 将javabean转为map类型，然后返回一个map类型的值
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!StringUtils.equals(name, "class")) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }
    
    /**
     * 取大文本的Json
     *
     * @param obj
     * @return
     */
    public static String getJsonStringClob(List obj) {
        
        for (int i = 0; i < obj.size(); i++) {
            Map json = (Map) obj.get(i);
            Set set = json.keySet();
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                Object value = (Object) json.get(key);
                boolean result = false;
                result = value instanceof oracle.sql.CLOB;
                if (result) {
                    oracle.sql.CLOB clob = (CLOB) value;
                    StringBuffer sb1 = new StringBuffer();
                    Reader instream;
                    try {
                        instream = clob.getCharacterStream();
                        BufferedReader in = new BufferedReader(instream);
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            sb1.append(line);
                        }
                        json.put(key, sb1.toString());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                    
                }
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        String resultStr = "{}";
        try {
            resultStr = mapper.writeValueAsString(obj);
            if (resultStr.indexOf("\":null,\"") > -1)
                resultStr = resultStr.replaceAll("\":null,\"", "\":\"\",\"");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultStr;
    }
    
    /**
     * 测试主方法
     *
     * @param args
     * @throws Exception
     */
    public static void main(String args[]) throws Exception {
        Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
        String url = "jdbc:sybase:Tds:192.168.1.180:5001/K_MS";
        Properties props = new Properties();
        props.put("user", "sa");
        props.put("password", "111111");
        Connection con = DriverManager.getConnection(url, props);
        DatabaseMetaData dmd = con.getMetaData();
        ResultSet rs = dmd.getTables(null, "%", "%", new String[]{"TABLE"});//
        while (rs.next()) {
            if (rs.getString(3).indexOf("$") > -1) {
                continue;
            }
        }
    }
}
